package xin.alum.aim.rabbitmq;


import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import xin.alum.aim.Aim;
import xin.alum.aim.constant.Constants;
import xin.alum.aim.groups.Session;
import xin.alum.aim.groups.SessionGroups;
import xin.alum.aim.groups.Sessions;
import xin.alum.aim.model.Events;
import xin.alum.aim.model.Notice;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.util.JSONUtils;


class RabbitMessageListener implements ChannelAwareMessageListener {

    private final Sessions sessions;

    private final SessionGroups groups;

    RabbitMessageListener(SessionGroups groups,Sessions sessions) {
        this.groups=groups;
        this.sessions = sessions;
    }

    @Override
    public void onMessage(Message message, Channel channel) {
        Transportable t;
        switch (message.getMessageProperties().getReceivedRoutingKey()) {
            case Constants.BIND_MESSAGE_INNER_QUEUE:
                sessions.kick(JSONUtils.fromJson(message.getBody(), Session.class));
                break;
            case Constants.PUSH_MESSAGE_INNER_QUEUE:
                t = JSONUtils.fromJson(message.getBody(), new TypeReference<Notice>() {
                });
                groups.get(t.getRecipient()).sends(t);
                break;
            case Constants.EVENT_MESSAGE_INNER_QUEUE:
                if (Aim.message != null) {
                    Aim.message.onMessage(message.getBody());
                } else {
                    t = JSONUtils.fromJson(message.getBody(), new TypeReference<Events>() {
                    });
                    if (t.getRecipient() == null || t.getRecipient().isEmpty() || t.getRecipient().equals(Sessions.ALL_SESSIONS)) {
                        sessions.sends(t);
                    } else {
                        groups.get(t.getRecipient()).sends(t);
                    }
                }
                break;
            default:
        }
    }
}
